# 文件名: elc_push
# 当前用户: shiping.zheng
# 当前日期: 2025/6/19
# 当前时间: 15:29
# 项目名称: Flag
"""
模块描述:
        使用python向巡天系统发送发电量
"""
import time
import json
import datetime
import paho.mqtt.client as mqtt
from apscheduler.schedulers.background import BackgroundScheduler

CLIENT_ID = 'mqttx_623dc277'
username = 'test'
password= 'TESTUSER123'
timeout= 1000
# MQTT服务器地址和端口
broker = "10.51.2.30"  # 替换为你的MQTT服务器地址
port = 1883  # MQTT默认端口

# 创建客户端时添加参数
client = mqtt.Client(
    protocol=mqtt.MQTTv5,  # 使用 MQTTv5
    callback_api_version=mqtt.CallbackAPIVersion.VERSION2  # 强制使用新版 Callback API
)
# 连接到MQTT服务器
client.connect(broker, port, 60)

# MQTT主题和消息
# topic = "v1/aishiwei/Inverter/SP00153QQ2520113/telemetry"  # 替换为你的主题

# 要发送的逆变器SN和厂商信息
device_map = {
    # "Z03M20302B7J160":"foxess",
    "410213831E34913800085":"kstar",
    # "HP005092323A0103":"aishiwei"
}

# 要发送的消息
message = {
    "INV.DeviceSn":'HP005092323A0103',
    "timestamp":"",
    "INV.APProduction":30956.4,
    "INV.ProductionDay":5,
    "INV.Pv_in_vol1":554,
    "INV.Pv_in_vol2":619.3,
    "INV.Pv_in_vol3":589.2,
    "INV.Pv_in_elec1":21.9,
    "INV.Pv_in_elec2":10.82,
    "INV.Pv_in_elec3":10.83,
    "INV.Pv_power":25.215,
    "INV.Pv_power1":12.133,
    "INV.Pv_power2":6.701,
    "INV.Pv_power3":6.381,
    "INV.TempAir":54,
    "INV.FreA":49.96,
    "INV.FreB":49.96,
    "INV.FreC":49.96,
    "INV.VolA":231.2,
    "INV.VolB":229.4,
    "INV.VolC":234.6,
    "INV.ElecA":35.2,
    "INV.ElecB":35.1,
    "INV.ElecC":35.4,
    "INV.power":24.483,
    "INV.power1":5.957,
    "INV.power2":5.894,
    "INV.power3":6.079,
    "INV.State":1,
    "INV.Power_of_Dc1":12.133,
    "INV.Power_of_Dc2_":6.701,
    "INV.Fault_value_of_R_phase_voltage":0,
    "INV.Fault_value_of_S_phase_voltage":0,
    "INV.Fault_value_of_T_phase_voltage":0,
    "INV.Fault_value_of_R_phase_frequency":0,
    "INV.Fault_value_of_S_phase_frequency":0,
    "INV.Fault_value_of_T_phase_frequency":0,
    "INV.Fault_value_of_PV1_voltage":0,
    "INV.Fault_value_of_PV2_voltage":0,
    "INV.Fault_value_of_temperature":0,
    "INV.Word_of_warning_message":0,
    "INV.Word_of_Manager_Fault_message":171, #告警信息
    "INV.PwRatio":1,
    "INV.Fac":49.96,
    "INV.device_model":"ASW30KC-LT-G2",
    "INV.device_version":"V610-03047-01",
    "INV.device_collector":"410262178E34915901212",
    "INV.device_collector_status":1,
    "INV.manufacturer":"aishiwei",
    "INV.capacity":30,
    "INV.Pv_string_elec1":100,
    "INV.Pv_string_vol1":200
}

def get_productionday():
    # 获取当前时间
    now = datetime.datetime.now()
    # 获取当天 0 点的时间
    midnight = now.replace(hour=0, minute=0, second=0, microsecond=0)
    # 计算从当天 0 点到现在过去的秒数
    seconds_since_midnight = (now - midnight).total_seconds()
    # 计算一天的总秒数
    total_seconds_per_day = 24 * 60 * 60
    # 计算 INV.ProductionDay 的值，范围在 0 到 25 之间
    production_day = (seconds_since_midnight / total_seconds_per_day) * 25
    return production_day

def send_messages():
    global client
    # 循环遍历 device_map，拿到key和值,循环推送
    for device_sn, manufacturer in device_map.items():
        # 复制原始 message 字典，避免修改原始数据
        new_message = message.copy()
        # 每次发送消息时更新 timestamp
        new_message["timestamp"] = int(time.time())
        new_message["INV.ProductionDay"] = get_productionday()
        # 替换 INV.DeviceSn 和 INV.manufacturer 字段
        new_message["INV.DeviceSn"] = device_sn
        new_message["INV.manufacturer"] = manufacturer
        # 组合新的 topic
        topic = f"v1/{manufacturer}/Inverter/{device_sn}/telemetry"
        # 将字典转换为 JSON 字符串
        message_json = json.dumps(new_message)
        # 发布消息到指定主题
        client.publish(topic, message_json)
        print(f"消息已发送到主题 {topic}: {message_json}")
        # 发布消息到指定主题
        client.publish(topic, message_json)
    # 断开连接
    # client.disconnect()

if __name__ == '__main__':
    scheduler = BackgroundScheduler()
    # 每 10 秒执行一次，对应的 cron 表达式 */10 * * * * *
    scheduler.add_job(send_messages, 'cron', second='*/10')
    scheduler.start()

    try:
        while True:
            time.sleep(2)
    except (KeyboardInterrupt, SystemExit):
        scheduler.shutdown()
        client.disconnect()
        print("程序已停止")



